// pages/info.js
var Api = require('../../utils/api.js');

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    wxInfoNo: true,
    num: 0,
    numList: [
      { name: '目标' },
      { name: '身高' },
      { name: '体重' },
      { name: '年龄' },
      { name: '完成' }
    ],
    target: ["增肥", "养生", "减肥"],
    targetValue: [1], // 默认选中的目标（例如：养生）
    height: Array.from({ length: 51 }, (_, i) => 150 + i), // 从150到200的身高选项
    heightValue: [10], // 默认选中160cm
    weight: Array.from({ length: 61 }, (_, i) => 40 + i), // 从40到100的体重选项
    weightValue: [20], // 默认选中60kg
    age: Array.from({ length: 100 }, (_, i) => i + 1), // 从1到100的年龄选项
    ageValue: [20], // 默认选中20岁
  },

  onShareAppMessage(o) {},

  onLoad: function (options) {
    var that = this;
    
    that.setData({
      num: options.num ? parseInt(options.num) : 0
    });
    
    // 从后端获取用户信息
    wx.request({
      url: Api.userInfo(),
      method: 'GET',
      success: function(res) {
        console.log("获取用户信息成功:", res.data);
        if (res.data) {
          const userInfo = res.data;
          // 根据后端数据设置picker的值
          const targetIdx = userInfo.target !== undefined && userInfo.target !== null ? userInfo.target : 1;
          const heightIdx = that.data.height.indexOf(userInfo.height) >= 0 ? that.data.height.indexOf(userInfo.height) : 10;
          const weightIdx = that.data.weight.indexOf(userInfo.weight) >= 0 ? that.data.weight.indexOf(userInfo.weight) : 20;
          const ageIdx = that.data.age.indexOf(userInfo.age) >= 0 ? that.data.age.indexOf(userInfo.age) : 20;
          
          that.setData({
            targetValue: [targetIdx],
            heightValue: [heightIdx],
            weightValue: [weightIdx],
            ageValue: [ageIdx]
          });
        }
      },
      fail: function(err) {
        console.error("获取用户信息失败:", err);
        // 使用默认值
        that.setData({
          targetValue: [1],
          heightValue: [10],
          weightValue: [20],
          ageValue: [20]
        });
      }
    });
  },

  numSteps() {
    var that = this;
    // 如果是最后一步，提交数据
    if (this.data.num === 3) {
      var params = {
        target: this.data.targetValue[0],
        height: this.data.height[this.data.heightValue[0]],
        weight: this.data.weight[this.data.weightValue[0]],
        age: this.data.age[this.data.ageValue[0]]
      };
      console.log("提交用户信息:", params);
      
      // 提交到后端
      wx.request({
        url: Api.userInfo(),
        method: 'PUT',
        data: params,
        success: function(res) {
          console.log("更新用户信息成功:", res.data);
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000,
            success: function() {
              // 跳转到个人中心
              setTimeout(function() {
                wx.switchTab({
                  url: '/pages/myself/myself'
                });
              }, 2000);
            }
          });
        },
        fail: function(err) {
          console.error("更新用户信息失败:", err);
          wx.showToast({
            title: '保存失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }
    // 更新到下一步
    var num = this.data.num === this.data.numList.length - 1 ? this.data.numList.length - 1 : this.data.num + 1;
    this.setData({ num: num });
  },

  // 绑定的选择事件
  bindTargetChange(e) {
    this.setData({ targetValue: e.detail.value });
  },
  bindHeightChange(e) {
    this.setData({ heightValue: e.detail.value });
  },
  bindWeightChange(e) {
    this.setData({ weightValue: e.detail.value });
  },
  bindAgeChange(e) {
    this.setData({ ageValue: e.detail.value });
  },

  bindGetUserInfo: function (e) {
    if (e.detail.errMsg !== "getUserInfo:ok") {
      wx.showToast({
        title: '授权失败',
        icon: 'none',
        duration: 2000
      });
    } else {
      wx.showToast({
        title: '授权成功',
        icon: 'success',
        duration: 2000
      });
    }
  }
});
